<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="openSearch = true"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['project:bomCalculator:in']"
        >
          导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport('child')"
          v-hasPermi="['project:bomCalculator:exportson']"
        >
          导出子表
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport('all')"
          v-hasPermi="['project:bomCalculator:exportall']"
        >
          全部导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          :disabled="selection.length == 0"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      highlight-current-row
      border
      stripe
      v-loading="tableData.loading"
      :data="tableData.rows"
      @row-click="getListChild"
      id="tabYpReport"
      @scrollBottom="load"
      height="calc(50% - 100px)"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <!-- <el-table-column label="#" width="40" type="index" align="center" /> -->
      <el-table-column
        label="预计日期"
        width="150"
        align="center"
        prop="predictTime"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.predictTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="物料代码"
        width="150"
        :show-overflow-tooltip="true"
        align="center"
        prop="wldm"
      />
      <el-table-column
        label="品名规格"
        align="center"
        prop="itmPmgg"
      ></el-table-column>
      <el-table-column
        label="预排数量"
        width="150"
        align="center"
        prop="qgsl"
      ></el-table-column>
      <el-table-column
        label="建立人员"
        width="150"
        align="center"
        prop="jlry"
      ></el-table-column>
      <el-table-column label="建立日期" width="150" align="center" prop="jlrq">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.jlrq, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
    </el-table>
    <el-table
      highlight-current-row
      border
      stripe
      v-loading="tableDataChild.load"
      :data="tableDataChild.rows"
      height="calc(50% - 50px)"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column label="#" width="40" type="se" align="center" />
      <el-table-column
        label="物料代码"
        align="center"
        prop="wldm"
      ></el-table-column>
      <el-table-column label="采购属性" width="140" align="center" prop="cgsx">
        <template #default="scope">
          <dict-tag :options="CgsxOptionss" :value="scope.row.cgsx" />
        </template>
      </el-table-column>
      <el-table-column
        label="最小包装"
        width="110"
        align="center"
        prop="minbz"
      ></el-table-column>
      <el-table-column
        label="请购数量"
        width="110"
        align="center"
        prop="qgsl"
      />
      <el-table-column
        label="建立人员"
        width="150"
        align="center"
        prop="jlry"
      ></el-table-column>
      <el-table-column label="建立日期" width="150" align="center" prop="jlrq">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.jlrq, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="预计时间"
        width="150"
        align="center"
        prop="predictTime"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.predictTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="客户代码"
        width="150"
        align="center"
        prop="itmCustwldm"
      ></el-table-column>
      <el-table-column
        label="品名规格"
        width="200"
        align="center"
        prop="itmPmgg"
      ></el-table-column>
      <el-table-column
        label="单位"
        :show-overflow-tooltip="true"
        width="60"
        align="center"
        prop="itmDw"
      >
        <template #default="scope">
          <dict-tag :options="unitFlagOptions" :value="scope.row.itmDw" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 查询对话框   -->
    <el-dialog
      title="查询"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="650px"
      append-to-body
    >
      <el-form :model="queryParams" ref="queryForm" label-width="125px">
        <el-col :span="12">
          <el-form-item label="预计日期:">
            <el-date-picker
              v-model="queryParams.predictTime"
              type="month"
              value-format="yyyy-MM"
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料代码" prop="wtWldm">
            <el-input v-model="queryParams.topWldm"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label-width="125px" prop="itmPmgg">
            <span slot="label">
              <el-tooltip
                content="综合查询包含物料代码，品名规格，客户编码查询"
                placement="top"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
              综合查询
            </span>
            <el-input v-model="queryParams.itmPmgg" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>
    <!-- 预排导入对话框   -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      :close-on-click-modal="false"
      width="400px"
      draggable
      append-to-body
    >
      <el-form label-width="80px">
        <el-form-item label="预计日期:">
          <el-date-picker
            v-model="upload.data.predictTime"
            type="month"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="00:00:00"
            clearable
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :data="upload.data"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">取 消</el-button>
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  getlistChild,
  exportList,
  exportChild,
  exportChildTotal,
  exportExample,
  handleDelete,
} from "@/api/project/bomCalculator.js";
import { getToken } from "@/utils/auth";
import { getAllCgList } from "@/api/project/mstr";
export default {
  name: "WalkThrough",
  data() {
    return {
      // 遮罩层

      exportLoading: false,
      openSearch: false,
      tableData: {
        rows: [],
        total: 0,
      },
      tableDataChild: {
        rows: [],
        loading: true,
        total: 0,
      },
      // 建立日期时间范围
      dateRange: [
        this.$moment().startOf("month").toDate(),
        this.$moment().endOf("month").toDate(),
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 40,
        wtDjbh: undefined,
        wtWldm: undefined,
        itmZxPmgg: "",
        itmPmgg: undefined,
        topWldm: undefined,
        predictTime: this.$moment().startOf("month").format("yyyy-MM"),
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "导入",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        data: {
          predictTime: this.$moment().format(),
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/project/calculator/import",
      },

      // 数据字典
      unitFlagOptions: [],
      CgsxOptionss: [],
      selection: [],
    };
  },
  created() {
    this.getDicts("sys_unit").then((response) => {
      this.unitFlagOptions = response.data;
    });
    //将不是字典的集合转为字典
    getAllCgList().then((response) => {
      this.CgsxOptionss = response.data;
      for (let i of this.CgsxOptionss) {
        i.dictLabel = i.cgName;
        i.dictValue = i.cgId + "";
        i.listClass = "default";
      }
    });
    this.getList();
  },
  watch: {
    dateRange(val, old) {
      if (val && val[1]) {
        this.queryParams.params.beginDate = val[0];
        this.queryParams.params.endDate = val[1];
      } else {
        this.queryParams.params = {};
      }
    },
  },
  methods: {
    /** 查询来料入库批退率列表 */
    getList() {
      getList(this.queryParams).then((response) => {
        this.tableData = response;
        this.getListChild(this.tableData.rows[0]);
      });
    },
    getListChild(row) {
      if (row) {
        this.selection = [row];
        getlistChild({ topWldmUid: row.topWldmUid }).then((response) => {
          this.tableDataChild.rows = response.data;
        });
      } else {
        this.tableDataChild.rows = [];
      }
    },
    //load
    load() {
      if (
        this.queryParams.pageNum <
        Math.ceil(this.tableData.total / this.queryParams.pageSize)
      ) {
        this.queryParams.pageNum++;
        getListWalkThrough(this.queryParams).then((response) => {
          this.tableData.rows = this.tableData.rows.concat(response.rows);
          this.tableData.total = response.total;
          this.loading = false;
        });
      }
      return 0;
    },
    // 取消按钮
    cancel() {
      this.openSearch = false;
    },
    handleDelete() {
      var ids = [];
      for (var i = 0; i < this.selection.length; i++) {
        ids.push(this.selection[i].topWldmUid);
      }
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return handleDelete(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleExport(val) {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          if (val == "all") {
            return exportChildTotal(queryParams);
          } else {
            if (this.selection.topWldmUid) {
              return exportChild({ topWldmUid: this.selection.topWldmUid });
            } else {
              this.$messages.error("请先选择一行主表数据!");
            }
          }
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
      this.openSearch = false;
    },
    handleImport() {
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      exportExample().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>

<style lang="scss" scoped></style>
